package com.xinchuang.domain.vo.byd;

import com.xinchuang.domain.type.NormalBYDQuotationaSubEnum;
import com.xinchuang.domain.type.NormalOutQuotationaSubEnum;
import com.xinchuang.domain.vo.qr.ManufacturingFee;
import com.xinchuang.domain.vo.qr.OtherFee;
import com.xinchuang.utils.BigdecimalUtil;
import com.xinchuang.utils.CheckUtil;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Objects;

/**
 * 制造成本
 */
@Data
public class ManufacturingFeeVo {
    //小计
    private double subTotal;
    //数据
    private List<ManufacturingFeeVo.DataList> dataList;

    @Data
    @AllArgsConstructor
    public class DataList {
        //项目
        private String itemName;
        //工时
        private double hour;
        //单价(元)
        private double price;
        //材料费
        private Double supplier;
        //金额(元)
        private double totalPrice;
    }

    public void checkFee() {

        BigDecimal subTotalAfter = new BigDecimal(0.00);
        String strType = NormalBYDQuotationaSubEnum.MANUFACTURING.getCn();
        //校验明细
        this.dataList.stream().allMatch(dataList -> {
            String type = strType + " " + dataList.getItemName() + " 金额";
            double v = BigdecimalUtil.calculateTotalPrice(dataList.getPrice(), dataList.getHour()).doubleValue();
            Double supplier = Objects.isNull(dataList.getSupplier()) ? 0D : dataList.getSupplier();
            double v1 = BigDecimal.valueOf(v).add(BigDecimal.valueOf(supplier)).setScale(2, RoundingMode.HALF_UP).doubleValue();
            return CheckUtil.checkIsEqual(type, dataList.getTotalPrice(), v1);
        });
        //检验小计
        for (DataList item : this.getDataList()) {
            BigDecimal totalPrice = calculateTotalPrice(item.getPrice(), item.getHour());
            Double supplier = Objects.isNull(item.getSupplier()) ? 0D : item.getSupplier();
            BigDecimal v1 = totalPrice.add(BigDecimal.valueOf(supplier)).setScale(2, RoundingMode.HALF_UP);
            subTotalAfter = subTotalAfter.add(v1);
        }
        checkSubTotal(strType, this.getSubTotal(), subTotalAfter.setScale(2, RoundingMode.HALF_UP));

    }

    /**
     * 计算总价
     *
     * @param param1 单价
     * @param param2 工时、数量
     * @return
     */
    private BigDecimal calculateTotalPrice(Double param1, Double param2) {
        BigDecimal totalPrice = new BigDecimal(param1).multiply(new BigDecimal(param2)).setScale(2, RoundingMode.HALF_UP);
        return totalPrice;
    }


    /**
     * 验证小计是否一致
     *
     * @param type          类型
     * @param subTotal      前端入参
     * @param subTotalAfter 后端计算
     */
    private void checkSubTotal(String type, Double subTotal, BigDecimal subTotalAfter) {
        if (subTotalAfter.compareTo(BigDecimal.valueOf(subTotal)) != 0) {
            throw new RuntimeException(type + "-小计计算结果不一致。结果为" + subTotalAfter);
        }
    }
}
